<template>
  <TableView class="table">
    <template #form>
      <NSpace
        justify="space-between"
        align="center"
      >
        <NSpace align="center">
          类型：
          <NInput
            style="width: 240rem"
            placeholder="请输入类型"
            v-model:value="paginationReactive.key"
            clearable
          ></NInput>
          状态：
          <NSelect
            style="width: 240rem"
            placeholder="请选择状态"
            v-model:value="paginationReactive.status"
            :options="[
              { label: '启用', value: 1 },
              { label: '停用', value: 2 }
            ]"
            clearable
          ></NSelect>
          <NButton
            type="primary"
            style="width: 78px"
            @click="queryTableData(true)"
            ghost
          >
            查询
          </NButton>
          <NButton
            type="primary"
            style="width: 78px"
            @click="resetValid()"
            ghost
          >
            重置
          </NButton>
        </NSpace>
        <NSpace align="center">
          <NButton
            type="primary"
            style="width: 78px"
            @click="handleAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>

    <template #table="props">
      <NDataTable
        v-bind="props"
        :bordered="false"
        :row-key="rowKey"
        :columns="columns"
        :data="tableData"
        :loading="tableLoading"
      />
    </template>

    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NDataTable,
  NPagination,
  NSpace,
  useMessage,
  NP,
  NModal,
  NSelect,
  NPopconfirm,
  NInput
} from 'naive-ui'
import { h, ref, reactive, watch, onDeactivated } from 'vue'
import type { DataTableColumns } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination } from '@/utils/http'
import type { customlistModel } from '@/api/office'
import { useViewerStore } from '../Common/store'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import upIcon from '@/assets/images/up_logo.png?url'
import lowIcon from '@/assets/images/low_logo.png?url'
import topIcon from '@/assets/images/top_logo.png?url'

const message = useMessage()
const route = useRoute()
const useStore = useViewerStore()

//表格
const rowKey: any = (e: any) => e.id || ''
const columns: DataTableColumns = [
  {
    fixed: 'left',
    title: '排序',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '20rem',
    align: useStore.isCenter
  },
  {
    title: '分类名称',
    key: 'menuName',
    width: '50rem',
    align: useStore.isCenter
  },
  {
    title: '状态',
    key: 'status',
    width: '20rem',
    align: useStore.isCenter,
    render: ({ status }) => {
      return status ? '启用' : '停用'
    }
  },
  {
    title: '创建人',
    key: 'createBy',
    width: '30rem',
    align: useStore.isCenter
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '50rem',
    align: useStore.isCenter
  },
  {
    title: '备注',
    key: 'notes',
    width: '100rem',
    align: useStore.isCenter
  },
  {
    title: '操作',
    key: 'action',
    align: useStore.isCenter,
    width: '75rem',
    fixed: 'right',
    render: (e: any, index: any) => [
      h(
        'div',
        {
          style: {
            display: 'flex',
            alignItems: 'center'
          }
        },
        {
          default: () => [
            h(
              NButton,
              { type: 'primary', quaternary: true, onClick: () => handleEdit(e) },
              {
                default: () => '编辑'
              }
            ),
            h(
              NPopconfirm,
              {
                onPositiveClick: () => changeStatus(e),
                onNegativeClick: () => console.log('negative'),
                negativeText: '取消',
                positiveText: '确定'
              },
              {
                default: () => `确定${e.status ? '停用' : '启用'}？`,
                trigger: () =>
                  h(
                    NButton,
                    { type: 'primary', quaternary: true },
                    {
                      default: () => (e.status ? '停用' : '启用')
                    }
                  )
              }
            ),
            h(
              NButton,
              {
                type: 'warning',
                quaternary: true,
                color: useStore.color['delete'],
                onClick: () => handleDelete(e?.id)
              },
              {
                default: () => '删除'
              }
            ),
            h(
              'img',
              {
                style: {
                  margin: '3px 15rem',
                  width: '16rem',
                  height: '16rem',
                  cursor: 'pointer',
                  // display: index + (paginationReactive.page - 1) * paginationReactive.pageSize ? 'inline' : 'none'
                  display: e.sort && e.sort != 1 ? 'inline' : 'none'
                },
                src: upIcon,
                onClick: () => handleMove(e.id, e.sort, 'up')
              },
              {
                default: () => upIcon
              }
            ),
            h(
              'img',
              {
                style: {
                  margin: '3px 15rem',
                  width: '16rem',
                  height: '16rem',
                  cursor: 'pointer',
                  // display: index + (paginationReactive.page - 1) * paginationReactive.pageSize + 1 != paginationReactive.itemCount ? 'inline' : 'none'
                  display: e.sort != paginationReactive.itemCount ? 'inline' : 'none'
                },
                src: lowIcon,
                onClick: () => handleMove(e.id, e.sort, 'low')
              },
              {
                default: () => lowIcon
              }
            ),
            h(
              'img',
              {
                style: {
                  margin: '3px 15rem',
                  width: '16rem',
                  height: '16rem',
                  cursor: 'pointer',
                  // display: index - 1 + (paginationReactive.page - 1) * paginationReactive.pageSize + 1 ? 'inline' : 'none'
                  display: e.sort != 1 ? 'inline' : 'none'
                },
                src: topIcon,
                onClick: () => handleMove(e.id, e.sort, 'top')
              },
              {
                default: () => topIcon
              }
            )
          ]
        }
      )
    ]
  }
]
// 页码
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  key: null,
  status: null,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
//新增
const handleAdd = () => router.push({ path: '/OA/Office/AddProcessType' })
// 编辑
const handleEdit = (val: any) =>
  router.push({ path: '/OA/Office/EditProcessType', query: { id: val.id } })
/**
 * 启用停用
 */
const changeStatus = async (row: any) => {
  console.log('row: ', row)
  const [error, res] = await sendRequest({
    module: 'customProcessConfig',
    api: 'updateWorkflowMenuStatus',
    override: {
      data: {
        id: row.id,
        status: !row.status
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(`${row.status ? '停用' : '启用'}成功`)
  tableData.value = []
  setTimeout(() => {
    queryTableData()
  }, 0)
}

//删除弹窗
const modalVisible = ref(false)
const modalId = ref()
const againDelete = async () => {
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'customProcessConfig',
    api: 'deleteWorkflowMenu',
    override: {
      params: {
        id: modalId.value
      }
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success('删除成功')
  modalVisible.value = false
  tableLoading.value = false
  tableData.value = []
  setTimeout(() => {
    queryTableData()
  }, 0)
}
// 删除
const handleDelete = (val: any) => {
  modalId.value = val
  modalVisible.value = true
}
/**
 * 移动行
 */
const handleMove = async (val: any, sort: number, direction: string) => {
  let newSort = null
  switch (direction) {
    case 'up':
      newSort = sort - 1 // sort 1开始
      break
    case 'low':
      newSort = sort + 1
      break
    case 'top':
      newSort = 1
      break
  }
  tableLoading.value = true
  const [error, res] = await sendRequest({
    module: 'customProcessConfig',
    api: 'moveWorkflowMenu',
    override: {
      data: {
        id: val,
        sort: newSort
      }
    }
  })
  if (error) return message.error(error.message), (tableLoading.value = false)
  if (res.code !== 0) return message.error(res.msg), (tableLoading.value = false)
  message.success(res.data)
  queryTableData()
}
/**
 * 重置查询条件
 */
const resetValid = () => {
  paginationReactive.key = null
  paginationReactive.status = null
}
//表格数据
const tableLoading = ref(false)
const tableData: any = ref([])
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<customlistModel[]>>({
    module: 'customProcessConfig',
    api: 'pageWorkflowMenu',
    override: {
      params: {
        page: paginationReactive.page,
        limit: paginationReactive.pageSize,
        key: paginationReactive.key,
        status: paginationReactive.status ? (paginationReactive.status == '1' ? true : false) : null
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  tableData.value = res.data.list
  console.log(' tableData.value: ', tableData.value)
  paginationReactive.itemCount = res.data.totalCount
}

const keyUpDown = (e: any) =>
  e.key == 'Enter' && ((paginationReactive.page = 1), queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))

watch(
  () => route.path,
  () => {
    if (route.path == '/OA/Office/customProcessTypeSetting') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
.table {
  height: 100%;
  padding: 29px 30px 42px;
}
</style>
